"""
文件上传相关视图
"""

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from drf_spectacular.utils import extend_schema, OpenApiResponse
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
import os
from datetime import datetime

from ..permissions import IsAdminUser


class ImageUploadView(APIView):
    """图片上传视图"""
    permission_classes = [IsAuthenticated, IsAdminUser]

    @extend_schema(
        summary='上传图片',
        description='上传单张图片',
        tags=['文件上传'],
        request={
            'multipart/form-data': {
                'type': 'object',
                'properties': {
                    'file': {
                        'type': 'string',
                        'format': 'binary',
                        'description': '图片文件'
                    }
                }
            }
        },
        responses={
            200: OpenApiResponse(
                description='上传成功',
                response={
                    'type': 'object',
                    'properties': {
                        'url': {'type': 'string', 'description': '图片 URL'},
                        'path': {'type': 'string', 'description': '图片路径'},
                    }
                }
            )
        }
    )
    def post(self, request):
        """上传图片"""
        file = request.FILES.get('file')
        if not file:
            return Response(
                {'error': '请提供图片文件'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 验证文件类型
        allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
        if file.content_type not in allowed_types:
            return Response(
                {'error': '不支持的图片格式，请上传 JPG、PNG、GIF 或 WebP 格式'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 验证文件大小（10MB）
        max_size = 10 * 1024 * 1024
        if file.size > max_size:
            return Response(
                {'error': '图片大小不能超过 10MB'},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 生成文件名
        ext = os.path.splitext(file.name)[1]
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f'uploads/{timestamp}_{file.name}'

        # 保存文件
        path = default_storage.save(filename, ContentFile(file.read()))
        url = request.build_absolute_uri(default_storage.url(path))

        return Response({
            'url': url,
            'path': path,
        })


class MultipleImageUploadView(APIView):
    """批量图片上传视图"""
    permission_classes = [IsAuthenticated, IsAdminUser]

    @extend_schema(
        summary='批量上传图片',
        description='一次上传多张图片',
        tags=['文件上传'],
        request={
            'multipart/form-data': {
                'type': 'object',
                'properties': {
                    'files': {
                        'type': 'array',
                        'items': {
                            'type': 'string',
                            'format': 'binary'
                        },
                        'description': '图片文件列表'
                    }
                }
            }
        },
        responses={
            200: OpenApiResponse(
                description='上传成功',
                response={
                    'type': 'object',
                    'properties': {
                        'files': {
                            'type': 'array',
                            'items': {
                                'type': 'object',
                                'properties': {
                                    'url': {'type': 'string'},
                                    'path': {'type': 'string'},
                                }
                            }
                        }
                    }
                }
            )
        }
    )
    def post(self, request):
        """批量上传图片"""
        files = request.FILES.getlist('files')
        if not files:
            return Response(
                {'error': '请提供图片文件'},
                status=status.HTTP_400_BAD_REQUEST
            )

        uploaded_files = []
        for file in files:
            # 验证文件类型
            allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
            if file.content_type not in allowed_types:
                continue

            # 验证文件大小（10MB）
            max_size = 10 * 1024 * 1024
            if file.size > max_size:
                continue

            # 生成文件名
            ext = os.path.splitext(file.name)[1]
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f'uploads/{timestamp}_{file.name}'

            # 保存文件
            path = default_storage.save(filename, ContentFile(file.read()))
            url = request.build_absolute_uri(default_storage.url(path))

            uploaded_files.append({
                'url': url,
                'path': path,
            })

        return Response({'files': uploaded_files})

